using UnityEngine;
using UnityEngine.U2D;

[ExecuteInEditMode]
public class EnvironmentGenerator : MonoBehaviour
{
    [SerializeField] private SpriteShapeController _spriteShapeController; // Sprite Shape 控制器
    [SerializeField, Range(3f, 100f)] private int _levelLength = 50; // 环境长度
    [SerializeField, Range(1f, 50f)] private float _xMultiplier = 2f; // X 倍增量
    [SerializeField, Range(1f, 50f)] private float _yMultiplier = 2f; // Y 倍增量
    [SerializeField, Range(0f, 1f)] private float _curveSmoothness = 0.5f; // 曲线平滑度
    [SerializeField] private float _noiseStep = 0.5f; // 噪声步长
    [SerializeField] private float _bottom = 10f; // 底部高度

    private Vector3 _lastPos; // 上一个位置

    public void OnValidate()
    {
        _spriteShapeController.spline.Clear(); // 清空曲线

        for (int i = 0; i < _levelLength; i++)
        {
            _lastPos = transform.position + new Vector3(i * _xMultiplier, Mathf.PerlinNoise(0, i * _noiseStep) * _yMultiplier, 0f); // 计算当前位置

            _spriteShapeController.spline.InsertPointAt(i, _lastPos); // 在曲线中插入点

            if (i != 0 && i != _levelLength - 1)
            {
                _spriteShapeController.spline.SetTangentMode(i, ShapeTangentMode.Continuous); // 设置切线模式为连续

                _spriteShapeController.spline.SetLeftTangent(i, Vector3.left * _xMultiplier * _curveSmoothness); // 设置左切线
                _spriteShapeController.spline.SetRightTangent(i, Vector3.right * _xMultiplier * _curveSmoothness); // 设置右切线
            }
        }

        _spriteShapeController.spline.InsertPointAt(_levelLength, new Vector3(_lastPos.x, transform.position.y - _bottom, 0f)); // 在最后添加底部左侧点
        _spriteShapeController.spline.InsertPointAt(_levelLength + 1, new Vector3(transform.position.x, transform.position.y - _bottom, 0f)); // 在最后添加底部右侧点
    }
}